package com.csd.serviceImpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.csd.dao.NewsDAO;
import com.csd.exception.DeleteException;
import com.csd.exception.GetException;
import com.csd.exception.SaveException;
import com.csd.exception.UpdateException;
import com.csd.helper.Tool;
import com.csd.pojo.News;
import com.csd.service.INewsService;

/**
 * 
 * Service：新闻
 * @author csd
 * @version 1.0
 * 
 * <br> 修订时间：2009-12-17
 * <br> 修改原因：创建文件
 * <br> 修改人：何文深
 * 
 * <br> 
 * 
 */
public class NewsService implements INewsService {

	private NewsDAO newsDAO;

	public NewsDAO getNewsDAO() {
		return newsDAO;
	}

	public void setNewsDAO(NewsDAO newsDAO) {
		this.newsDAO = newsDAO;
	}

	/**
	 * 添加一条新闻
	 * 
	 * @param news
	 *            新闻对象
	 * @return true为添加成功，false为失败
	 */
	public boolean addNews(News news) {
		boolean bl = false;
		try {
			news.setTime(Tool.getCurrentDate());
			newsDAO.save(news);
			bl = true;
		} catch (RuntimeException e) {
			throw new SaveException(e,"新闻保存出错");

		}
		return bl;
	}

	/**
	 * 删除一条新闻
	 * 
	 * @param newsID
	 *            新闻id
	 * @return true为删除成功，false为失败
	 */
	public boolean deleteNews(Integer newsID) {
		News news = new News();
		news.setId(newsID);
		try {
			newsDAO.delete(news);
		} catch (RuntimeException e) {
			throw new DeleteException(e,"新闻删除失败");			
		}
		return true;
	}

	/**
	 * 新闻列表，查询所有新闻
	 * 
	 * @return 新闻对象列表
	 */
	public List<News> listNews() {
		List<News> newsList = null;
		List<News> temp = null;
		try {

			temp = newsDAO.findAll();
			if (temp != null) {
				if(newsList == null)
					newsList = new ArrayList<News>();
				for (Iterator iterator = temp.iterator(); iterator.hasNext();) {
					News news = (News) iterator.next();
					newsList.add(news);
				}
			}
		} catch (RuntimeException e) {
			throw new GetException(e,"查询失败");
			
		}
		return newsList;
	}

	/**
	 * 获取一条新闻的详细信息
	 * 
	 * @param newsID
	 *            新闻id
	 * @return 新闻对象，若查询不到则返回null
	 */
	public News searchNews(Integer newsID) {
		News news = new News();
		news.setId(newsID);
		News temp = null;

		try {
			temp = (News) newsDAO.findById(newsID);
		} catch (Exception e) {
			throw new GetException(e,"查询失败");
		}
		return temp;
	}
	/**
	 * 更新一条新闻
	 * 
	 * @param newsID
	 *            新闻id
	 * @return boolean
	 */
	public boolean updateNews(News news) {
		try {
			if(news != null && newsDAO.findById(news.getId()) != null)
			{
				newsDAO.updateNews(news);
			}
			
			return true;
		} catch (RuntimeException e) {
			e.printStackTrace();
		    throw new UpdateException(e,"更新失败");
		}

	}
}
